#include "Common.h"
#include "SystemV/AppLibSystemV_Sem.hpp"

#include <signal.h>

static 	SINT32 g_SemId = -1;

void signal_deal(int signo)
{
    ULONG ulRet = STAT_SUCCESS;

	ulRet = AppLibSystemV_SemDestory(&g_SemId);
    printf("[%s %d] AppLibSystemV_SemDestory ret=%lu\n", __func__, __LINE__, ulRet);

    exit(-1);
}

void signal_register(void)
{
    signal(SIGHUP,  signal_deal);
    signal(SIGINT,  signal_deal);
    signal(SIGQUIT, signal_deal);
    signal(SIGPIPE, signal_deal);
    signal(SIGALRM, signal_deal);
    signal(SIGTERM, signal_deal);
    signal(SIGSEGV, signal_deal);
}

int main (int argc, char **args)
{
    int i = 0;
	ULONG uRet = STAT_SUCCESS; 

    signal_register();

	if (argc != 2)
	{
		printf("Usage: ./SystemV_SemSrv <Path>");
		return -1;
	}

	uRet = AppLibSystemV_SemCreate(args[1], 1, &g_SemId);
	if (uRet != STAT_SUCCESS)
	{
		printf("[%s %d] AppLibSystemV_SemCreate ret=%lu\n", __func__, __LINE__, uRet);
		return -2;
	}

	uRet = AppLibSystemV_SemSetVal(g_SemId, 0, 1);
	if (uRet != STAT_SUCCESS)
	{
		printf("[%s %d] AppLibSystemV_SemSetVal ret=%lu\n", __func__, __LINE__, uRet);
        AppLibSystemV_SemDestory(&g_SemId);
		return -3;
	}

    while (1)
    {
        AppLibSystemV_SemP_Wait(g_SemId, 0);
		printf("[%s %d] AppLibSystemV_SemSrv %d\n", __func__, __LINE__, ++i);
        usleep(100 * 1000);
    }

	return 0;
}
